<script setup lang="tsx">
import { ContentWrap } from '@/components/ContentWrap'
import { Search } from '@/components/Search'
import { onMounted, ref } from 'vue'
import { Table } from '@/components/Table'
import { useRouter } from 'vue-router'
import { BaseButton } from '@/components/Button'
import {
  SysFileTransferCenterListVo,
  SysTransferCenterListVo,
  SysTransferCenterSearchQo
} from '@/api/system/file/SysTransferCenter/types'
import {
  sysTransferCenterDeleteApi,
  sysTransferCenterPackageDownloadApi,
  sysTransferCenterPageApi
} from '@/api/system/file/SysTransferCenter'
import { AllSchemas, useBasePageView } from '@/base/views/BasePageView'
import { TableSortProps } from '@/components/Table/src/types'
import { ElText, ElTable, ElTableColumn, ElButton } from 'element-plus'
import { sysDictChooseListApi } from '@/api/system/dict/SysDict'
import { KeyLabelValueVo } from '@/base/api/KeyLabelValueVo'
import { selectSysAccountNameListApi } from '@/api/system/account/SysAccount'
import {sysFileDownloadApi} from "@/api/system/file/SysFile";
// [[ OnflowGenerator Range (- selectFunctionImport -) Start ]]

// [[ OnflowGenerator Range (- selectFunctionImport -) End ]]

defineOptions({
  name: 'SysTransferCenterPage'
})
const { push } = useRouter()

const pageView = useBasePageView<SysTransferCenterListVo, SysTransferCenterSearchQo>(
  'SysTransferCenter'
)
const {
  pageInfo,
  delLoading,
  loading,
  dataList,
  baseGetList,
  searchParams,
  baseSortChange,
  datePickerShortcuts,
  registerRefreshEvent,
  editUrl,
  addUrl
} = pageView

const getList = async (params: any) => {
  await baseGetList(params, sysTransferCenterPageApi)
}
pageView.doWatch(getList)
// [[ OnflowGenerator Range (- dictFunctions -) Start ]]
const transferTypeOptions = ref<Array<KeyLabelValueVo>>([])
const getTransferType = async () => {
  const res = await sysDictChooseListApi('sysTransferCenterTransferType')
  transferTypeOptions.value = res.data
}
getTransferType()
const executeStateOptions = ref<Array<KeyLabelValueVo>>([])
const getExecuteState = async () => {
  const res = await sysDictChooseListApi('sysTransferCenterExecuteState')
  executeStateOptions.value = res.data
}
getExecuteState()
const platformTypeOptions = ref<Array<KeyLabelValueVo>>([])
const getPlatformType = async () => {
  const res = await sysDictChooseListApi('platformType')
  platformTypeOptions.value = res.data
}
getPlatformType()
const moduleNameOptions = ref<Array<KeyLabelValueVo>>([])
const getModuleName = async () => {
  const res = await sysDictChooseListApi('sysModuleName')
  moduleNameOptions.value = res.data
}
getModuleName()

// [[ OnflowGenerator Range (- dictFunctions -) End ]]

// [[ OnflowGenerator Range (- selectFunctions -) Start ]]

// [[ OnflowGenerator Range (- selectFunctions -) End ]]

const sysAccountNameList = ref<Array<KeyLabelValueVo>>([])
const getSysAccountNameList = async () => {
  const res = await selectSysAccountNameListApi({})
  sysAccountNameList.value = res.data
}
getSysAccountNameList()

const delData = async (row: SysTransferCenterListVo | null) => {
  await pageView.delData(row, sysTransferCenterDeleteApi, () => {
    getList({ ...searchParams.value })
  })
}

const sortChange = async (sortProps: TableSortProps) => {
  await baseSortChange(sortProps, sysTransferCenterPageApi)
}

const allSchemas = ref<AllSchemas>({
  searchSchema: [
    // [[ OnflowGenerator Range (- searchSchemas -) Start ]]
    {
      field: 'id',
      label: '主键id',
      component: 'InputNumber',
      componentProps: {
        placeholder: '请选择主键id',
        clearable: true
      }
    },
    {
      field: 'name',
      label: '任务名称',
      component: 'Input',
      componentProps: {
        placeholder: '请输入任务名称',
        clearable: true
      }
    },
    {
      field: 'transferType',
      label: '传输类型',
      component: 'Select',
      componentProps: {
        placeholder: '请选择传输类型',
        clearable: true,
        filterable: true,
        options: transferTypeOptions
      }
    },
    {
      field: 'executeState',
      label: '执行状态',
      component: 'Select',
      componentProps: {
        placeholder: '请选择执行状态',
        clearable: true,
        filterable: true,
        options: executeStateOptions
      }
    },
    {
      field: 'platformType',
      label: '平台类型',
      component: 'Select',
      componentProps: {
        placeholder: '请选择平台类型',
        clearable: true,
        filterable: true,
        options: platformTypeOptions
      }
    },
    {
      field: 'fileCount',
      label: '文件数量',
      component: 'Input',
      componentProps: {
        placeholder: '请输入文件数量',
        clearable: true
      }
    },
    {
      field: 'moduleName',
      label: '所属模块',
      component: 'Select',
      componentProps: {
        placeholder: '请选择所属模块',
        clearable: true,
        filterable: true,
        options: moduleNameOptions
      }
    },
    {
      field: 'successCount',
      label: '成功数量',
      component: 'Input',
      componentProps: {
        placeholder: '请输入成功数量',
        clearable: true
      }
    },
    {
      field: 'failCount',
      label: '失败数量',
      component: 'Input',
      componentProps: {
        placeholder: '请输入失败数量',
        clearable: true
      }
    },
    {
      field: 'skipCount',
      label: '跳过数量',
      component: 'Input',
      componentProps: {
        placeholder: '请输入跳过数量',
        clearable: true
      }
    },
    {
      field: 'errorMessage',
      label: '错误信息',
      component: 'Input',
      componentProps: {
        placeholder: '请输入错误信息',
        clearable: true
      }
    },
    {
      field: 'startTime',
      label: '任务开始时间',
      component: 'DatePicker',
      componentProps: {
        placeholder: '请选择任务开始时间',
        clearable: true,
        type: 'datetimerange',
        valueFormat: 'YYYY-MM-DD HH:mm:ss',
        shortcuts: datePickerShortcuts
      }
    },
    {
      field: 'finishTime',
      label: '任务结束时间',
      component: 'DatePicker',
      componentProps: {
        placeholder: '请选择任务结束时间',
        clearable: true,
        type: 'datetimerange',
        valueFormat: 'YYYY-MM-DD HH:mm:ss',
        shortcuts: datePickerShortcuts
      }
    },
    {
      field: 'createTime',
      label: '创建时间',
      component: 'DatePicker',
      componentProps: {
        placeholder: '请选择创建时间',
        clearable: true,
        type: 'datetimerange',
        valueFormat: 'YYYY-MM-DD HH:mm:ss',
        shortcuts: datePickerShortcuts
      }
    },
    {
      field: 'updateTime',
      label: '更新时间',
      component: 'DatePicker',
      componentProps: {
        placeholder: '请选择更新时间',
        clearable: true,
        type: 'datetimerange',
        valueFormat: 'YYYY-MM-DD HH:mm:ss',
        shortcuts: datePickerShortcuts
      }
    },
    // [[ OnflowGenerator Range (- searchSchemas -) End ]]
    {
      field: 'createUser',
      label: '创建人',
      component: 'Select',
      componentProps: {
        placeholder: '请选择创建人',
        clearable: true,
        filterable: true,
        options: sysAccountNameList
      }
    },
    {
      field: 'updateUser',
      label: '更新人',
      component: 'Select',
      componentProps: {
        placeholder: '请选择更新人',
        clearable: true,
        filterable: true,
        options: sysAccountNameList
      }
    }
  ],
  tableColumns: [
    {
      field: 'selection',
      type: 'selection'
    },
    {
      field: 'expand',
      type: 'expand',
      slots: {
        default: (data: any) => {
          return (
            <div class="secondary-table" style={{'padding-left': '25px','padding-right': '25px'}}>
              <ElTable data={data.row.files}>
                <ElTableColumn label="文件名" prop="fileName" />
                <ElTableColumn label="文件大小" prop="fileSizeName" />
                <ElTableColumn
                    label="操作"
                    v-slots={{
                      default: (scope: any) => ( // 使用 v-slots 定义默认插槽，并通过回调函数接收 scope 参数
                          <ElButton
                              type="primary"
                              size="small"
                              onClick={() => {
                                downloadSingleFile(scope.row) // 现在可以正确访问到 scope.row
                              }}
                          >
                            下载
                          </ElButton>
                      ),
                    }}
                ></ElTableColumn>
              </ElTable>
            </div>
          )
        }
      }
    },
    {
      field: 'index',
      label: '序号',
      type: 'index',
      search: {
        hidden: true
      },
      form: {
        hidden: true
      },
      detail: {
        hidden: true
      }
    },
    // [[ OnflowGenerator Range (- tableColumns -) Start ]]
    {
      field: 'name',
      label: '任务名称',
      sortable: 'custom'
    },
    {
      field: 'transferType',
      label: '传输类型',
      sortable: 'custom',
      slots: {
        default: (data: any) => {
          return (
            <>
              <div>{data.row.transferTypeName}</div>
            </>
          )
        }
      }
    },
    {
      field: 'executeState',
      label: '执行状态',
      sortable: 'custom',
      slots: {
        default: (data: any) => {
          return (
            <>
              <div>{data.row.executeStateName}</div>
            </>
          )
        }
      }
    },
    {
      field: 'platformType',
      label: '平台类型',
      sortable: 'custom',
      slots: {
        default: (data: any) => {
          return (
            <>
              <div>{data.row.platformTypeName}</div>
            </>
          )
        }
      }
    },
    {
      field: 'fileCount',
      label: '文件数量',
      sortable: 'custom'
    },
    {
      field: 'moduleName',
      label: '所属模块',
      sortable: 'custom',
      slots: {
        default: (data: any) => {
          return (
            <>
              <div>{data.row.moduleNameName}</div>
            </>
          )
        }
      }
    },
    {
      field: 'successCount',
      label: '成功数量',
      sortable: 'custom'
    },
    {
      field: 'failCount',
      label: '失败数量',
      sortable: 'custom'
    },
    {
      field: 'skipCount',
      label: '跳过数量',
      sortable: 'custom'
    },
    {
      field: 'errorMessage',
      label: '错误信息',
      sortable: 'custom'
    },
    {
      field: 'startTime',
      label: '任务开始时间',
      sortable: 'custom'
    },
    {
      field: 'finishTime',
      label: '任务结束时间',
      sortable: 'custom'
    },
    {
      field: 'createTime',
      label: '创建时间',
      sortable: 'custom'
    },
    {
      field: 'updateTime',
      label: '更新时间',
      sortable: 'custom'
    },
    // [[ OnflowGenerator Range (- tableColumns -) End ]]
    {
      field: 'createUserName',
      label: '创建人',
      sortable: 'custom'
    },
    {
      field: 'updateUserName',
      label: '更新人',
      sortable: 'custom'
    },
    {
      field: 'action',
      width: '260px',
      label: '操作',
      slots: {
        default: (data: any) => {
          return (
            <>
              <BaseButton type="primary" onClick={() => editData(data.row)} permission="'edit'">
                编辑
              </BaseButton>
              {data.row.packageDownloadUrl && (
                <BaseButton
                  type="success"
                  onClick={() => packageDownload(data.row)}
                  permission="'download'"
                >
                  打包下载
                </BaseButton>
              )}
              <BaseButton type="danger" onClick={() => delData(data.row)} permission="'delete'">
                删除
              </BaseButton>
            </>
          )
        }
      }
    }
  ]
})

const editData = (row: SysTransferCenterListVo) => {
  push(`${editUrl}?id=${row.id}&type=edit`)
}

const addAction = () => {
  push(`${addUrl}?type=add`)
}

const packageDownload = async (row: SysTransferCenterListVo) => {
  await sysTransferCenterPackageDownloadApi(row.id)
}

const downloadSingleFile = async (row: SysFileTransferCenterListVo) => {
  await sysFileDownloadApi(row.id)
}

onMounted(() => {
  getList({})
  registerRefreshEvent(sysTransferCenterPageApi)
})
</script>

<template>
  <ContentWrap>
    <Search
      :schema="allSchemas.searchSchema"
      @search="getList"
      @reset="getList"
      expandField="id"
      :searchLoading="loading"
      :resetLoading="loading"
    />

    <div class="mb-10px">
      <BaseButton type="primary" @click="addAction" permission="'add'">新增</BaseButton>
      <BaseButton :loading="delLoading" type="danger" @click="delData(null)" permission="'delete'">
        删除
      </BaseButton>
    </div>

    <Table
      v-model:pageSize="pageInfo.pageSize"
      v-model:currentPage="pageInfo.currentPage"
      :columns="allSchemas.tableColumns"
      :data="dataList"
      :loading="loading"
      :stripe="true"
      :pagination="{
        total: pageInfo.totalCount
      }"
      @register="pageView.tableRegister"
      @sort-change="sortChange"
    />
  </ContentWrap>
</template>

<style lang="less" scoped>
.secondary-table {
  margin: 20px;
  padding: 20px;
}
</style>
